package org.l.qiao.file;

import org.l.qiao.Cluster;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 严秋旺 on 2014/11/27.
 */
public class Limit {

    private static final Logger LOGGER = Logger.getLogger(Limit.class);
    private String file = "/WEB-INF/limit.xml";
    private String path = "";
    private List<Cluster> limit = new ArrayList<>();

    public Limit() {
        path = ServletActionContext.getServletContext().getRealPath(file);
    }

    public Limit(String path) {
        this.path = path;
    }

    /**
     * 加载limit.xml文件
     *
     * @return 是否成功
     */
    public boolean load() {
        if (path == null) {
            LOGGER.error("权限配置文件不存在：" + file);
            return false;
        }
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(path);
            Element root = document.getRootElement();
            for (Object o : root.elements()) {
                limit.add(readPackage((Element) o));
            }
            return true;
        } catch (DocumentException e) {
            LOGGER.error("权限配置文件读取异常：" + e.getMessage());
            return false;
        }
    }

    private Cluster readPackage(Element ele) {
        Cluster packageMap = new Cluster();
        packageMap.put("name", ele.attributeValue("name"));
        List<Map<String, Object>> action = new ArrayList<Map<String, Object>>();
        for (Object o : ele.elements()) {
            action.add(readAction((Element) o));
        }
        packageMap.put("action", action);
        return packageMap;
    }

    private Map<String, Object> readAction(Element ele) {
        Map<String, Object> actionMap = new HashMap<>();
        actionMap.put("name", ele.attributeValue("name"));
        actionMap.put("key", ele.attributeValue("key"));
        List<Map<String, Object>> page = new ArrayList<>();
        for (Object o : ele.elements()) {
            Element p = (Element) o;
            Map<String, Object> pageMap = new HashMap<>();
            pageMap.put("name", p.attributeValue("name"));
            pageMap.put("value", p.attributeValue("value"));
            page.add(pageMap);
        }
        actionMap.put("page", page);
        return actionMap;
    }

    public List<Cluster> getLimit() {
        return limit;
    }
}
